package edu.usx.server.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.mysql.cj.protocol.x.XMessage;
import edu.usx.server.pojo.RespBean;
import edu.usx.server.pojo.Sites;
import edu.usx.server.mapper.SitesMapper;
import edu.usx.server.pojo.*;
import edu.usx.server.pojo.vo.SitesVO;
import edu.usx.server.service.ISitesService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import static edu.usx.server.pojo.RespBean.success;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Usx
 * @since 2024-07-18
 */
@Service
@RequiredArgsConstructor
public class SitesServiceImpl extends ServiceImpl<SitesMapper, Sites> implements ISitesService {

    private final SitesMapper sitesMapper;

    /**
     * @description: 获取服务信息，封装成VO实体列表返回
     * @author: Elapse
     * @date: 2024/7/23
     * @return: List<SitesVO>
     **/
    @Override
    public List<SitesVO> getSiteVOList() {
        return sitesMapper.selectSiteVOList();
    }

    /**
     * @description: 获取服务信息，封装成VO实体返回
     * @author: Elapse
     * @date: 2024/7/23
     * @return: SitesVO
     **/
    @Override
    public SitesVO getSiteVOById(Integer id) {
        return sitesMapper.selectSiteVOById(id);
    }



    @Override
    public RespBean Search(PageQueryDTO key) {
        QueryWrapper<Sites> queryWrapper = new QueryWrapper<>();
        //只查询审核通过已上架的网站
        queryWrapper.eq("status",1);
        // 如果页码或页面大小非法，设置默认值
        if (key.getPagenum() <= 0) {
            key.setPagenum(1);
        }
        if (key.getPagesize() <= 0) {
            key.setPagesize(10); // 默认页面大小为 10
        }

        PageHelper.startPage((int)key.getPagenum(), (int)key.getPagesize());
        // 添加关键字查询条件
        if (StringUtils.isNotBlank(key.getKeyword())) {
            queryWrapper.and(wrapper -> wrapper.like("name", key.getKeyword())
                    .or().like("description", key.getKeyword())
                    .or().like("category_id", key.getKeyword()));
        }

        // 添加排序条件
        if (StringUtils.isNotBlank(key.getKeyword())) {
            switch (key.getKeyword()) {
                case "name":
                    queryWrapper.orderByAsc("name");
                    break;
                case "category_id":
                    queryWrapper.orderByDesc("rating");
                    break;
                // 可根据需要添加其他排序方式
                default:
                    // 默认按照 ID 倒序排列
                    queryWrapper.orderByDesc("id");
                    break;
            }
        } else {
            // 默认按照 ID 倒序排列
            queryWrapper.orderByDesc("id");
        }
        List<Sites> sitesList = sitesMapper.selectList(queryWrapper);
        PageInfo<Sites> pageInfo = new PageInfo<>(sitesList);
        long total = pageInfo.getTotal();
        Integer totalPages = (int) Math.ceil((double) total / key.getPagesize());

        // 如果 pageNum 超出总页数，调整为最后一页
        if (key.getPagenum() > totalPages && totalPages > 0) {
            key.setPagenum(totalPages);
            PageHelper.startPage(key.getPagenum(), key.getPagesize());
            sitesList = sitesMapper.selectList(queryWrapper);
        }
        PageDTO<Sites> pageDTO = new PageDTO<>();
        pageDTO.setResults(sitesList);
        pageDTO.setHasMore(key.getPagenum() < totalPages);
        edu.usx.server.pojo.PageInfo pageInfo1=new edu.usx.server.pojo.PageInfo(key.getPagenum(), key.getPagesize(), totalPages);
        pageDTO.setPage(pageInfo1);

        return success("查询成功", pageDTO);
    }
    /**
     * @description: 更新服务信息
     * @author: Elapse
     * @date: 2024/7/18
     * @return: RespBean
     **/
    @Override
    @Transactional
    public RespBean updateSiteInfo(Sites site) {
        /*获取用户信息*/
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        /*获取用户id*/
        Integer updateUser = user.getId();
        /*判断是否为管理员或创建者*/
        if (!updateUser.equals(getById(site.getId()).getCreateUser())) {
            return RespBean.error("该账户非该服务的创建者");
        }
        /*更新信息*/
        LocalDateTime updateTime = LocalDateTime.now();
        boolean update = lambdaUpdate()
                /*名称修改*/
                .set(site.getName() != null, Sites::getName, site.getName())
                /*分类修改*/
                .set(site.getCategoryId() != null, Sites::getCategoryId, site.getCategoryId())
                /*描述修改*/
                .set(site.getDescription() != null, Sites::getDescription, site.getDescription())
                /*图标修改*/
                .set(site.getIcon() != null, Sites::getIcon, site.getIcon())
                /*链接修改*/
                .set(site.getLink() != null, Sites::getLink, site.getLink())
                /*状态修改*/
                .set(Sites::getStatus, SiteStatus.OFFLINE)
                /*更新者与更新时间*/
                .set(Sites::getUpdateUser, updateUser)
                .set(Sites::getUpdateTime, updateTime)
                /*条件判断*/
                .eq(Sites::getId, site.getId())
                .lt(Sites::getUpdateTime, updateTime)
                .update();
        if (!update) {
            return RespBean.error("服务信息更新失败");
        }
        return success("成功更新服务信息");
    }

    /**
     * @description: 审核服务状态（管理员）
     * @author: Elapse
     * @date: 2024/7/19
     * @return: RespBean
     **/
    @Override
    @Transactional
    public RespBean updateSiteStatus(Sites site) {
        /*获取用户信息*/
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        /*获取用户id*/
        Integer updateUser = user.getId();
        /*获取用户权限*/
        Integer userRole = user.getRole_id();
        Integer adminRole = 1;
        if (!userRole.equals(adminRole) ) {
            return RespBean.error("账户权限不足");
        }
        /*修改状态*/
        LocalDateTime updateTime = LocalDateTime.now();
        boolean update = lambdaUpdate()
                /*状态更改*/
                .set(site.getStatus() != null, Sites::getStatus, site.getStatus())
                /*更新者与更新时间*/
                .set(updateUser != null, Sites::getUpdateUser, updateUser)
                .set(Sites::getUpdateTime, updateTime)
                .eq(Sites::getId, site.getId())
                .lt(Sites::getUpdateTime, updateTime)
                .update();
        if (!update) {
            return RespBean.error("服务状态更新失败");
        }
        return success("成功更新服务状态");
    }


    public List<String> getLink(Integer create_user) {
        return sitesMapper.getLinkByCreateUser(create_user);
    }

    public Boolean addLink(Sites sites, Integer create_user) {
        List<String> linkList = getLink(create_user);

        for (String link : linkList) {
            if (sites.getLink().equals(link) == true) {
                throw new IllegalStateException("link: " + sites.getLink() + " already exist");
            }
        }

        sitesMapper.addLinkByCreateUser(sites.getName(), sites.getCategoryId(), sites.getStatus(), sites.getLink(), sites.getCreateUser(), sites.getDescription(), sites.getIcon(), sites.getUpdateUser(), sites.getCreateTime(), sites.getUpdateTime());
        return true;
    }

}
